﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Collections.Concurrent;
using FinPlusCommon;

namespace FinPlusComponents
{
    public class FinPlusLevel 
    {
        public double Value { get; private set; }
        public DateTime TimeStamp { get { return _timeStamp; } }

        private enum Params { BuySell, Level }
        private readonly ConcurrentDictionary<string, IFunction> _level;
        private readonly string _buySell;
        private DateTime _timeStamp;

        //construct
        public FinPlusLevel(string buySell)
        {
            _level = new ConcurrentDictionary<string, IFunction>();
            _buySell = buySell;
            _timeStamp = DateTime.MinValue;
            Value = double.NaN;
        }

        //public
        public bool LevelUpdate(IFunction level)
        {
            var prevValue = Value;
            IFunction level1, level2;
            var buySell = level[Params.BuySell.ToString()].ToString();
            _level[buySell] = level;

            if (_buySell.Equals("Mid") && _level.TryGetValue(_buySell, out level1))
                Value = (double)level1.Value(Params.Level.ToString());
            else if (_buySell.Equals("Mid") && _level.TryGetValue("Buy", out level1) && _level.TryGetValue("Sell", out level2))
                Value = ((double)level1.Value(Params.Level.ToString()) + (double)level2.Value(Params.Level.ToString())) / 2;
            else if (_buySell.Equals("Last") && _level.TryGetValue(_buySell, out level1))
                Value = (double)level1.Value(Params.Level.ToString());
            else if (_buySell.Equals("Sell") && _level.TryGetValue(_buySell, out level1))
                Value = (double)level1.Value(Params.Level.ToString());
            else if (_buySell.Equals("Buy") && _level.TryGetValue(_buySell, out level1))
                Value = (double)level1.Value(Params.Level.ToString());
            else
                Value = double.NaN;

            _timeStamp = level.Get(Params.Level.ToString()).TimeStamp;

            return !prevValue.Equals(Value);
        }
    }
}
